package cn.itsource.controller;

import cn.itsource.domain.User;
import cn.itsource.service.IMailService;
import cn.itsource.service.IUserService;
import cn.itsource.util.JSONResult;
import cn.itsource.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class UserController {

    @Autowired
    private IUserService UserService;
    @Autowired
    private IMailService mailService;

    // 登录
    @PostMapping("login")
    public JSONResult login(@RequestBody User user){
        try {
            // 生成token令牌
            String token = UserService.login(user.getUsername(), user.getPassword());
            // 返回生成的令牌
            return JSONResult.ok("登陆成功", token);
        }catch (RuntimeException e){
            e.printStackTrace();
//            返回错误信息
            return JSONResult.fail(e.getMessage());
        }
    }

    // 注册
    @PostMapping("enroll")
    public JSONResult sendMail(@RequestBody User user){
        // 判断前端请求是否有验证码，没有则仅发送验证码
        if (user.getCode()==null){
            // 发送对应邮箱的验证码
            mailService.sendMail(user.getEmail());
            return JSONResult.ok();
        }else {
            // 如果有验证码则和保存的验证码进行比较
            try {
                // 如果验证码验证通过生成token令牌
                String token = UserService.enroll(user);
                // 返回生成的令牌
                return JSONResult.ok("注册成功", token);
            }catch (RuntimeException e){
                e.printStackTrace();
                // 返回错误信息
                return JSONResult.fail(e.getMessage());
            }
        }

        }

}
